package com.gosuncn.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;


import javax.sql.DataSource;

/**
 * springboot启动自动执行sql脚本
 */
@Configuration
public class CustomizeDataSourceInitialize {

    /**
     * 初始化sql
     */
    @Value("classpath:sql/init.sql")
    private Resource sqlInit;

    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource){
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator(){
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(sqlInit);
        //如果存在多个sql可以执行多个addScript
//        resourceDatabasePopulator.addScript(sqlInit);
        resourceDatabasePopulator.setSeparator(";");
        return resourceDatabasePopulator;
    }
}
